<template>
  <div class="NewAddrress">
    <van-nav-bar :title="aid?'编辑地址':'新增地址'" left-text="返回" left-arrow @click-left="onClickLeft" fixed />
    <van-address-edit class="address-box" :area-list="areaList" show-postal :show-delete="!!aid" show-set-default :area-columns-placeholder="['选择省', '选择市', '选择区']" @save="onSave" @delete="onDelete" :address-info="addressInfo" save-button-text="保存地址" />
  </div>
</template>

<script>
import areaList from '@/assets/js/area.js'
import request from '@/utils/reques'
import qs from 'qs'
export default {
  name: 'NewAddress',

  data() {
    return {
      areaList,
      // 地址的初始值
      addressInfo: {},
      // 地址的aid
      aid: ''
    }
  },
  created() {
    this.aid = this.$route.query.aid
    if (this.aid) {
      this.getAddressDataByAid()
    }
  },

  methods: {
    // 修改购物车数量
    changeShopbagCount() {
      request.post('/modifyShopcartCount', qs.stringify({}))
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    // 保存地址
    onSave(content) {
      let tokenString = localStorage.getItem('token')

      if (!tokenString) {
        this.$toast('请先登录~')
        return this.$router.push({ name: 'Login' })
      }

      //  复制地址content
      let addressInfo = Object.assign({}, content)
      delete addressInfo.country
      addressInfo.tokenString = tokenString
      addressInfo.appkey = this.appkey
      addressInfo.isDefault = Number(addressInfo.isDefault)
      this.$toast.loading({
        message: '获取信息中',
        forbidClick: true,
        duration: 0
      })
      // 有aid是编辑地址，没有aid是新增地址
      if (!this.aid) {
        // 新增地址
        this.address(addressInfo, '/addAddress')
      } else {
        // 编辑地址
        // 验证用户是否修改过原地址的数据
        let isModify = false
        for (let key in this.addressInfo) {
          if (content[key] != this.addressInfo[key]) {
            isModify = true
          }
        }
        if (isModify) {
          this.address(addressInfo, '/editAddress')
        } else {
          return this.$toast('请修改地址信息')
        }
      }
    },
    // 发起新增地址编辑地址的请求
    async address(addressInfo, url) {
      try {
        const { data: res } = await request.post(url, qs.stringify(addressInfo))
        if (res.code == 700) {
          this.$router.push({ name: 'Login' })
        } else if (res.code == 9000 || res.code == 30000) {
          setTimeout(() => {
            this.$router.push({ name: 'Myaddress' })
          }, 500)
        }
        this.$toast(res.msg)
        this.$toast.clear()
      } catch (error) {
        this.$toast.clear()
      }
    },
    // 删除地址
    async onDelete() {
      try {
        let tokenString = localStorage.getItem('token')

        if (!tokenString) {
          this.$toast('请先登录~')
          return this.$router.push({ name: 'Login' })
        }

        this.$toast.loading({
          message: '获取信息中',
          forbidClick: true,
          duration: 0
        })
        const { data: res } = await request.post('/deleteAddress', qs.stringify({ appkey: this.appkey, tokenString, aid: this.aid }))
        if (res.code == 700) {
          this.$router.push({ name: 'Login' })
        } else if (res.code == 10000) {
          setTimeout(() => {
            this.$router.push({ name: 'Myaddress' })
          }, 500)
        }
        this.$toast(res.msg)
      } catch (error) {
        this.$toast.clear()
      }
    },
    async getAddressDataByAid() {
      try {
        let tokenString = localStorage.getItem('token')

        if (!tokenString) {
          this.$toast('请先登录~')
          return this.$router.push({ name: 'Login' })
        }

        this.$toast.loading({
          message: '获取信息中',
          forbidClick: true,
          duration: 0
        })
        const { data: res } = await request.get('/findAddressByAid', {
          params: {
            appkey: this.appkey,
            tokenString,
            aid: this.aid
          }
        })
        // console.log(res)
        if (res.code == 700) {
          this.$router.push({ name: 'Login' })
        } else if (res.code == 40000) {
          let data = res.result[0]
          data.isDefault = Boolean(data.isDefault)
          this.addressInfo = data
        }
        this.$toast.clear()
      } catch (error) {
        this.$toast.clear()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.address-box {
  margin-top: 50px;
}
/deep/ .van-button--danger {
  height: 42px;
  border-radius: 20px;
  background-color: #1a73e8;
  border: #1a73e8;
}
</style>